package com.example.controller;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.utils.R;
import com.example.entity.Notice;
import com.example.entity.Params;
import com.example.service.NoticeService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/notice")
@Api(tags = "公告管理")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;

    @PostMapping
    @ApiOperation(value = "添加公告", notes = "根据公告ID判断是新增还是更新公告")
    public R update(@RequestBody Notice notice) {
        if (ObjectUtil.isEmpty(notice.getId())) {
            noticeService.add(notice);
        } else {
            noticeService.update(notice);
        }
        return R.success();
    }

    @GetMapping
    @ApiOperation(value = "获取最新公告", notes = "获取所有最新的公告")
    public R findTop() {
        List<Notice> list = noticeService.findTop();
        return R.success(list);
    }

    @GetMapping("/search")
    @ApiOperation(value = "根据条件搜索公告", notes = "根据传入的搜索参数查找公告，支持分页")
    public R findBySearch(Params params) {
        PageInfo<Notice> info = noticeService.findBySearch(params);
        return R.success(info);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除公告", notes = "根据公告ID删除公告")
    public R delete(@PathVariable Integer id) {
        noticeService.delete(id);
        return R.success();
    }
}
